import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures

# 设置随机种子以获得可重现的结果
np.random.seed(0)

# 生成合成数据
X = np.sort(np.random.rand(100, 1), axis=0)             # 随机生成100个x值，排序
y = 3 - 2 * X ** 2 + X + np.random.randn(100, 1) * 0.5  # y值是X的非线性函数，加上一些噪声

# 绘制原始数据
plt.scatter(X, y)
plt.title('Synthetic Data')
plt.xlabel('X')
plt.ylabel('Y')
plt.show()

# 多项式回归
poly_features = PolynomialFeatures(degree=20, include_bias=False)

# 将X转换为多项式特征
X_poly = poly_features.fit_transform(X)

# 使用线性回归模型
model = LinearRegression()
model.fit(X_poly, y)

# 绘制拟合曲线
X_fit = np.linspace(X.min(), X.max(), 100).reshape(100, 1)
X_fit_poly = poly_features.transform(X_fit)
y_fit = model.predict(X_fit_poly)

plt.scatter(X, y, label='Data')
plt.plot(X_fit, y_fit, color='red', label='Polynomial Regression Fit')
plt.title('Polynomial Regression')
plt.xlabel('X')
plt.ylabel('Y')
plt.legend()
plt.show()
